package net.goutalk.glcs.module.workflow.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import net.goutalk.glcs.common.constant.GlobalConstant;
import net.goutalk.glcs.common.model.result.R;
import net.goutalk.glcs.module.workflow.entity.WorkflowRecord;
import net.goutalk.glcs.module.workflow.service.IWorkflowRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  流程记录前端控制器
 * </p>
 *
 * @author tanyujie
 * @since 2022-10-13
 */
@RestController
@RequestMapping(GlobalConstant.WORKFLOW_MODULE_PREFIX + "/record")
@Api(value = GlobalConstant.WORKFLOW_MODULE_PREFIX + "/record", tags = "流程记录接口")
@AllArgsConstructor
public class WorkflowRecordController {

    private final IWorkflowRecordService workflowRecordService;

    private final HistoryService historyService;

    /**
     * 数据库存储xml字段的后缀
     */
    private static final String DB_FIELD_XML_PREFIX = "xml";

    @GetMapping("/list")
    @ApiOperation(value = "查询整个流程的流程记录")
    public R list(@RequestParam String processInstanceId){

        List<HistoricProcessInstance> subProcess = historyService.createHistoricProcessInstanceQuery()
                .superProcessInstanceId(processInstanceId).list();

        List<String> subProcessIds = subProcess.stream().map(HistoricProcessInstance::getId).collect(Collectors.toList());

        subProcessIds.add(processInstanceId);

        LambdaQueryWrapper<WorkflowRecord> queryWrapper = Wrappers.lambdaQuery(WorkflowRecord.class).in(WorkflowRecord::getProcessId, subProcessIds).orderByDesc(WorkflowRecord::getId);

        return R.ok(workflowRecordService.list(queryWrapper));
    }
}